<template>
  <picker-view indicator-style="height: 40px;" :value="checkValue" @change="bindChange" class="picker-view">
    <picker-view-column id="1">
      <view class="item" v-for="(item,index) in provinces" :key="index">{{item.areaName}}</view>
    </picker-view-column>
    <picker-view-column id="2">
      <view class="item" v-for="(item,index) in citys" :key="index">{{item.areaName}}</view>
    </picker-view-column>
  </picker-view>
</template>

<script setup>
import provinceData from "@/config/provinceData.json";

const props = defineProps({
  formData: {
    type: Object,
    default: () => {},
  },
});

const checkValue = ref([0, 0]);
const isChange = ref(false);
const provinces = reactive(provinceData);
const citys = ref(provinceData[0]?.children);

// 获取当前选中的省市区各自的 index
const currentRegion = () => {
  if (props.formData.region) {
    const region = props.formData.region.split(",");
    const pIndex = provinces?.findIndex((v) => v.areaName == region[0]);
    citys.value = provinces[pIndex]?.children;
    const cIndex = citys.value?.findIndex((v) => v.areaName == region[1]);
    return [pIndex, cIndex];
  }
  return [0, 0];
};

// 监测切换省份  重置对应市区数据
watch(
  () => checkValue.value[0],
  (v) => {
    if (v && isChange.value) getRegion([v, 0]);
  }
);

// 滑动选择
const bindChange = (e) => {
  isChange.value = true;
  const val = e.detail.value;
  getRegion(val);
};

// 获取citys and  赋值region
const getRegion = (val = []) => {
  citys.value = provinces[val[0]]?.children;

  let province = "";
  let city = "";
  province = provinces[val[0]]?.areaName;
  city = citys.value[val[1]]?.areaName;
  props.formData.region = `${province},${city}`;
};

onMounted(() => {
  const val = currentRegion();
  nextTick(() => {
    checkValue.value = val;
    getRegion(val);
  });
});
</script>

<style lang=scss scoped>
.picker-view {
  width: 100%;
  height: 560rpx;
  margin: 60rpx 0;
}
.divider {
  color: #999;
  font-size: 40rpx;
  font-weight: 400;
}
.item {
  line-height: 80rpx;
  text-align: center;
  font-weight: bold;
  font-size: 40rpx;
}
</style>